package gripper.ftp.handle;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.Callable;

import gripper.ftp.DataSocket;
import gripper.ftp.FtpSession;
import gripper.ftp.PathConvert;

public class RETRHandle implements Handle {
	FtpSession ftpSession;

	public RETRHandle(FtpSession ftpSession) {
		this.ftpSession = ftpSession;
	}

	public void process(String line, BufferedReader br, final OutputStream os) throws IOException {
		os.write("150 Opening BINARY mode data connection\r\n".getBytes());
		os.flush();
		final DataSocket sock = ftpSession.getClientSock();
		String[] splited = line.split(" ");
		if (splited == null || splited.length < 2) {
			os.write("226 Transfer complete.\r\n".getBytes());
			os.flush();
			sock.close();
			return;
		}
		String fileName = splited[1].trim();
		fileName = ftpSession.currentDir + "/" + fileName;
		fileName = PathConvert.toServerPath(ftpSession.getRootDir(), fileName);
		final File file = new File(fileName);
		if (!file.exists()) {
			os.write("226 Transfer complete.\r\n".getBytes());
			os.flush();
			sock.close();
			return;
		}
		ftpSession.submit(new Callable<String>() {

			@Override
			public String call() throws Exception {
				OutputStream outputStream = sock.getOutputStream();
				try (FileInputStream fileIn = new FileInputStream(file);) {
					byte[] buf = new byte[4096];
					while (!ftpSession.abort.get()) {
						int len = fileIn.read(buf);
						if (len < 0) {
							break;
						}
						outputStream.write(buf, 0, len);
					}
				} catch (Exception e) {

				}
				outputStream.flush();
				os.write("226 Transfer complete.\r\n".getBytes());
				os.flush();
				sock.close();
				ftpSession.abort.set(false);
				return null;
			}
		});

	}

}
